<?php

/**
 * @package Nina
 * @author John Main <john@thedaddy.org>
 */
abstract class Nina_Model_Category extends Nina_Model
{
	/**
	 * Set the lineage while saving
	 * @param boolean [$replace=false] SQL replace instead of insert
	 * @return boolean
	 */
	public function save($replace = false) {
		$this->setLineage($this->getParents());
		return parent::save($replace);
	}

	/**
	 * Get the title with all parent titles
	 * @return string
	 */
	public function getTitleWithParents() {
		$parents = $this->getParentTitles();
		
		if($parents)
			return $this->getTitle() . ' - ' . $parents;
		else
			return $this->getTitle();
	}

	/**
	 * Get all parent titles
	 * @return string
	 */
	public function getParentTitles() {
		if($this->getParentId() && ($parent = $this->getParent()))
			return $parent->getTitleWithParents();
		else
			return '';
	}

	/**
	 * Get all parent IDs
	 * @return string
	 */
	public function getParents() {
		if($this->getParentId() && ($parent = $this->getParent()))
			return $parent->getPk() . '-' . $parent->getParents();
		else
			return 0;
	}

	/**
	 * Get the categories
	 * @param string|false [$controller=false] Get for the given controller
	 * @param integer|false[$except=false] Exclude the given PK
	 * @return array
	 */
	public static function get($controller = false, $except = false) {
		$c = self::newCriteria();
		
		if($controller) {
			$c->addJoin('Category::ID', 'Item::CATEGORY_ID');
			$c->add(Item::CONTROLLER, $controller);
		}
		
		if($except)
			$c->add(Category::ID, $except, Nina_Orm_Criteria::NOT_EQUAL);

		$c->addOrderBy(Category::TITLE, Nina_Orm_Criteria::ORDER_ASC);
		return self::doSelect(new Category(), $c, false, true);
	}

	/**
	 * Parse the list of categories into a format suitable for a select box
	 * @param string|false [$controller=false] Get for the given controller
	 * @param integer|false[$except=false] Exclude the given PK
	 * @return array
	 */
	public static function getForSelect($controller = false, $except = false) {
		$results = array();

		if(($categories = self::get($controller, $except))) {
			foreach($categories as $category) {
				$results[] = array($category->getTitleWithParents(), $category->getPk());
			}
		}
		
		return $results;
	}
}
